package com.lianjia.analysis.controller.api;

import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.axis.Axis;
import com.github.abel533.echarts.axis.CategoryAxis;
import com.github.abel533.echarts.axis.ValueAxis;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.data.Data;
import com.github.abel533.echarts.series.Line;
import com.github.abel533.echarts.series.Scatter;
import com.github.abel533.echarts.series.Series;
import com.lianjia.analysis.model.HouseInfo;
import com.lianjia.analysis.service.HousePriceAnalysisService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 房价分析API控制器
 * 提供给前端使用的API接口
 */
@RestController
@RequestMapping("/api/analysis")
@Tag(name = "房价分析API", description = "提供房价数据分析相关的API")
public class AnalysisApiController {

    private static final Logger logger = LoggerFactory.getLogger(AnalysisApiController.class);

    private final HousePriceAnalysisService housePriceAnalysisService;

    @Autowired
    public AnalysisApiController(HousePriceAnalysisService housePriceAnalysisService) {
        this.housePriceAnalysisService = housePriceAnalysisService;
    }

    /**
     * 获取系统概览数据
     */
    @GetMapping("/overview")
    @Operation(summary = "获取系统概览数据", description = "返回系统整体的概览数据，包括房源总数、平均价格、平均面积、覆盖区域数等")
    public ResponseEntity<Map<String, Object>> getOverview() {
        logger.info("获取系统概览数据");
        
        Map<String, Object> result = new HashMap<>();
        
        // 获取房源总数
        Map<String, Integer> cityHouseCount = housePriceAnalysisService.getCityHouseCount();
        int totalHouses = cityHouseCount.values().stream().mapToInt(Integer::intValue).sum();
        result.put("totalHouses", totalHouses);
        
        // 获取平均价格
        Map<String, Double> cityAvgPrice = housePriceAnalysisService.getCityAveragePrice();
        double avgPrice = cityAvgPrice.values().stream().mapToDouble(Double::doubleValue).average().orElse(0);
        result.put("avgPrice", avgPrice);
        
        // 计算平均面积
        // 这里简化处理，实际应该从数据库计算
        result.put("avgArea", 89.5);
        
        // 覆盖区域数
        result.put("districtsCount", 16);
        
        // 区域分布数据
        List<Map<String, Object>> districtDistribution = new ArrayList<>();
        Map<String, Integer> mockDistribution = new HashMap<>();
        mockDistribution.put("浦东", 1200);
        mockDistribution.put("徐汇", 800);
        mockDistribution.put("静安", 750);
        mockDistribution.put("长宁", 600);
        mockDistribution.put("黄浦", 580);
        mockDistribution.put("其他", 1500);
        
        for (Map.Entry<String, Integer> entry : mockDistribution.entrySet()) {
            Map<String, Object> item = new HashMap<>();
            item.put("name", entry.getKey());
            item.put("value", entry.getValue());
            districtDistribution.add(item);
        }
        result.put("districtDistribution", districtDistribution);
        
        // 价格区间分布
        List<Map<String, Object>> priceDistribution = new ArrayList<>();
        String[] ranges = {"0-50万", "50-100万", "100-150万", "150-200万", "200-300万", "300-500万", "500万以上"};
        int[] counts = {120, 350, 580, 780, 950, 620, 430};
        
        for (int i = 0; i < ranges.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("range", ranges[i]);
            item.put("count", counts[i]);
            priceDistribution.add(item);
        }
        result.put("priceDistribution", priceDistribution);
        
        // 价格趋势数据
        List<Map<String, Object>> priceTrend = new ArrayList<>();
        String[] dates = {"2024-01", "2024-02", "2024-03", "2024-04", "2024-05", "2024-06"};
        double[] prices = {3.25, 3.28, 3.32, 3.35, 3.38, 3.42};
        
        for (int i = 0; i < dates.length; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("date", dates[i]);
            item.put("price", prices[i]);
            priceTrend.add(item);
        }
        result.put("priceTrend", priceTrend);
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取筛选选项
     */
    @GetMapping("/options")
    @Operation(summary = "获取筛选选项", description = "获取指定城市的筛选选项，包括区域、户型、装修等")
    public ResponseEntity<Map<String, Object>> getOptions(
            @Parameter(description = "城市名称，默认为上海") @RequestParam(required = false) String city) {
        logger.info("获取筛选选项，城市={}", city);
        
        // 如果未指定城市，默认使用上海
        String cityName = city != null ? city : "上海";
        
        Map<String, Object> result = new HashMap<>();
        
        // 区域选项 - 从MongoDB获取
        List<String> districts = housePriceAnalysisService.getDistrictsByCity(cityName);
        result.put("districts", districts);
        
        // 户型选项 - 从MongoDB获取
        Map<String, Map<String, Integer>> layoutDistribution = housePriceAnalysisService.getCityLayoutDistribution();
        Map<String, Integer> cityLayouts = layoutDistribution.getOrDefault(cityName, new HashMap<>());
        List<String> layouts = new ArrayList<>(cityLayouts.keySet());
        result.put("layouts", layouts);
        
        // 装修选项 - 从MongoDB获取
        Map<String, Map<String, Integer>> decorationDistribution = housePriceAnalysisService.getCityDecorationDistribution();
        Map<String, Integer> cityDecorations = decorationDistribution.getOrDefault(cityName, new HashMap<>());
        List<String> decorations = new ArrayList<>(cityDecorations.keySet());
        result.put("decorations", decorations);
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取房源列表
     */
    @GetMapping("/houses")
    @Operation(summary = "获取房源列表", description = "根据条件筛选房源列表，支持分页")
    public ResponseEntity<Map<String, Object>> getHouses(
            @Parameter(description = "区域") @RequestParam(required = false) String district,
            @Parameter(description = "户型") @RequestParam(required = false) String layout,
            @Parameter(description = "装修") @RequestParam(required = false) String decoration,
            @Parameter(description = "最小面积") @RequestParam(required = false) Double minArea,
            @Parameter(description = "最大面积") @RequestParam(required = false) Double maxArea,
            @Parameter(description = "最低总价") @RequestParam(required = false) Double minPrice,
            @Parameter(description = "最高总价") @RequestParam(required = false) Double maxPrice,
            @Parameter(description = "最低单价") @RequestParam(required = false) Double minUnitPrice,
            @Parameter(description = "最高单价") @RequestParam(required = false) Double maxUnitPrice,
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") int size) {
        
        logger.info("获取房源列表，筛选条件：district={}, layout={}, decoration={}, minArea={}, maxArea={}, minPrice={}, maxPrice={}, minUnitPrice={}, maxUnitPrice={}, page={}, size={}",
                district, layout, decoration, minArea, maxArea, minPrice, maxPrice, minUnitPrice, maxUnitPrice, page, size);
        
        // 调用服务查询房源
        List<HouseInfo> houses = housePriceAnalysisService.searchHouses("上海", minPrice, maxPrice, minArea, maxArea, layout, district);
        
        // 分页处理
        int start = page * size;
        int end = Math.min(start + size, houses.size());
        List<HouseInfo> pageContent = start < houses.size() ? houses.subList(start, end) : new ArrayList<>();
        
        Map<String, Object> result = new HashMap<>();
        result.put("content", pageContent);
        result.put("totalElements", houses.size());
        result.put("totalPages", (int) Math.ceil((double) houses.size() / size));
        result.put("size", size);
        result.put("number", page);
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 获取图表数据
     */
    @GetMapping("/charts")
    @Operation(summary = "获取图表数据", description = "获取各种图表数据，包括散点图、柱状图等")
    public ResponseEntity<Map<String, Object>> getCharts(
            @Parameter(description = "区域") @RequestParam(required = false) String district,
            @Parameter(description = "户型") @RequestParam(required = false) String layout,
            @Parameter(description = "装修") @RequestParam(required = false) String decoration,
            @Parameter(description = "最小面积") @RequestParam(required = false) Double minArea,
            @Parameter(description = "最大面积") @RequestParam(required = false) Double maxArea,
            @Parameter(description = "最低总价") @RequestParam(required = false) Double minPrice,
            @Parameter(description = "最高总价") @RequestParam(required = false) Double maxPrice,
            @Parameter(description = "最低单价") @RequestParam(required = false) Double minUnitPrice,
            @Parameter(description = "最高单价") @RequestParam(required = false) Double maxUnitPrice) {
        
        try {
            logger.info("获取图表数据，筛选条件：district={}, layout={}, decoration={}, minArea={}, maxArea={}, minPrice={}, maxPrice={}, minUnitPrice={}, maxUnitPrice={}",
                    district, layout, decoration, minArea, maxArea, minPrice, maxPrice, minUnitPrice, maxUnitPrice);
            
            Map<String, Object> result = new HashMap<>();
            
            // 获取面积与价格散点图数据
            Option scatterOption = housePriceAnalysisService.getPriceAreaScatterData("上海");
            
            // 直接提取散点图数据
            List<Map<String, Object>> scatterData = new ArrayList<>();
            
            if (scatterOption != null && scatterOption.series() != null && !scatterOption.series().isEmpty()) {
                for (Series series : scatterOption.series()) {
                    if (series instanceof Scatter) {
                        Scatter scatter = (Scatter) series;
                        List<Object> dataPoints = scatter.data();
                        
                        if (dataPoints != null) {
                            for (Object dataPoint : dataPoints) {
                                if (dataPoint instanceof Object[]) {
                                    Object[] point = (Object[]) dataPoint;
                                    if (point.length >= 2) {
                                        if (point[0] instanceof Number && point[1] instanceof Number) {
                                            Map<String, Object> pointMap = new HashMap<>();
                                            pointMap.put("area", ((Number) point[0]).doubleValue());
                                            pointMap.put("price", ((Number) point[1]).doubleValue());
                                            scatterData.add(pointMap);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            result.put("scatterData", scatterData);
            
            // 获取户型分布数据
            Map<String, Map<String, Integer>> layoutDistribution = housePriceAnalysisService.getCityLayoutDistribution();
            Map<String, Integer> shanghaiLayout = layoutDistribution.getOrDefault("上海", new HashMap<>());
            
            List<Map<String, Object>> layoutData = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : shanghaiLayout.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", entry.getKey());
                item.put("value", entry.getValue());
                layoutData.add(item);
            }
            result.put("layoutData", layoutData);
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取图表数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 获取价格趋势数据
     */
    @GetMapping("/price-trends")
    @Operation(summary = "获取价格趋势数据", description = "返回指定城市的月度价格趋势数据")
    public ResponseEntity<Map<String, Object>> getPriceTrends(
            @RequestParam @Parameter(description = "城市名称") String city) {
        try {
            logger.info("API调用开始: /api/analysis/price-trends, 参数: city={}", city);
            long startTime = System.currentTimeMillis();
            
            // 获取城市价格趋势数据
            Option trendOption = housePriceAnalysisService.getCityPriceTrend(city);
            
            // 构建结果
            Map<String, Object> result = new HashMap<>();
            result.put("city", city);
            
            // 从X轴获取日期数据
            List<String> dates = new ArrayList<>();
            if (trendOption != null && trendOption.xAxis() != null && trendOption.xAxis().size() > 0) {
                Axis xAxis = trendOption.xAxis().get(0);
                if (xAxis instanceof CategoryAxis) {
                    List<Object> dateList = ((CategoryAxis) xAxis).data();
                    if (dateList != null) {
                        for (Object d : dateList) {
                            dates.add(d.toString());
                        }
                    }
                }
            }
            
            // 从数据系列获取价格数据
            List<Double> prices = new ArrayList<>();
            if (trendOption != null && trendOption.series() != null && !trendOption.series().isEmpty()) {
                Series series = trendOption.series().get(0);
                if (series instanceof Line) {
                    List<Object> priceList = ((Line) series).data();
                    if (priceList != null) {
                        for (Object p : priceList) {
                            if (p instanceof Number) {
                                double price = ((Number) p).doubleValue();
                                prices.add(price);
                            }
                        }
                    }
                }
            }
            
            result.put("months", dates);
            result.put("prices", prices);
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/price-trends, 城市: {}, 耗时: {}ms", city, (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取价格趋势数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 获取房源详情
     */
    @GetMapping("/house/{id}")
    @Operation(summary = "获取房源详情", description = "根据ID获取房源详细信息")
    public ResponseEntity<HouseInfo> getHouseDetail(
            @Parameter(description = "房源ID") @PathVariable String id) {
        logger.info("获取房源详情，id={}", id);
        
        // 模拟从数据库获取房源详情
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setId(id);
        houseInfo.setTitle("精装修三室两厅，南北通透，近地铁");
        houseInfo.setCityName("上海");
        houseInfo.setDistrict("浦东");
        
        // 使用Map设置户型信息
        Map<String, String> details = new HashMap<>();
        details.put("layout", "3室2厅");
        details.put("area", "89平米");
        details.put("areaValue", "89");
        details.put("orientation", "南北");
        details.put("decoration", "精装");
        details.put("floor", "中层/18层");
        details.put("buildYear", "2015年");
        details.put("buildType", "板楼");
        houseInfo.setDetails(details);
        
        return ResponseEntity.ok(houseInfo);
    }
    
    /**
     * 获取房源价格分析
     */
    @GetMapping("/house-price-analysis/{id}")
    @Operation(summary = "获取房源价格分析", description = "获取特定房源的价格分析数据")
    public ResponseEntity<?> getHousePriceAnalysis(@PathVariable @Parameter(description = "房源ID") String id) {
        try {
            logger.info("API调用开始: /api/analysis/house-price-analysis/{}, 参数: id={}", id, id);
            long startTime = System.currentTimeMillis();
            
            // 获取房源信息 - 使用模拟数据
            HouseInfo house = null;
            try {
                // 尝试通过ID查找房源
                List<HouseInfo> houses = housePriceAnalysisService.searchHouses(null, null, null, null, null, null, null);
                for (HouseInfo h : houses) {
                    if (id.equals(h.getId())) {
                        house = h;
                        break;
                    }
                }
                logger.debug("房源查找结果: found={}", house != null);
            } catch (Exception e) {
                logger.warn("获取房源信息异常", e);
            }
            
            if (house == null) {
                // 创建模拟房源数据
                house = new HouseInfo();
                house.setId(id);
                house.setTitle("精装修三室两厅，南北通透，近地铁");
                house.setCityName("上海");
                house.setDistrict("浦东");
                house.setCommunity("XX花园");
                
                // 使用Map设置价格和面积
                Map<String, String> details = new HashMap<>();
                details.put("layout", "3室2厅");
                details.put("area", "89平米");
                details.put("orientation", "南北");
                details.put("decoration", "精装");
                details.put("floor", "中层/18层");
                details.put("buildYear", "2015年");
                house.setDetails(details);
                logger.debug("使用了模拟房源数据");
            }
            
            String city = house.getCityName();
            String district = house.getDistrict();
            String community = house.getCommunity();
            
            // 获取总价和单价（模拟数据）
            double totalPrice = 580.0;
            double unitPrice = 65000.0;
            
            // 获取面积
            String areaText = house.getDetails().get("area");
            double area = 0.0;
            if (areaText != null) {
                try {
                    area = Double.parseDouble(areaText.replaceAll("[^0-9.]", ""));
                } catch (NumberFormatException e) {
                    area = 89.0;  // 默认值
                    logger.warn("面积转换异常: {}", areaText, e);
                }
            }
            
            // 获取户型
            String layout = house.getDetails().get("layout");
            
            Map<String, Object> result = new HashMap<>();
            result.put("id", id);
            result.put("title", house.getTitle());
            result.put("city", city);
            result.put("district", district);
            result.put("community", community);
            result.put("totalPrice", totalPrice);
            result.put("unitPrice", unitPrice);
            result.put("area", area);
            result.put("layout", layout);
            
            // 获取城市平均价格
            Map<String, Double> cityAvgPrices = housePriceAnalysisService.getCityAveragePrice();
            double cityAvgPrice = cityAvgPrices.getOrDefault(city, 0.0);
            result.put("cityAvgPrice", cityAvgPrice);
            
            // 获取区域平均价格（模拟数据）
            double districtAvgPrice = unitPrice * 0.9;  // 假设小区均价是该房源价格的90%
            result.put("districtAvgPrice", districtAvgPrice);
            
            // 获取社区平均价格（模拟数据）
            double communityAvgPrice = unitPrice * 0.95;  // 假设社区均价是该房源价格的95%
            result.put("communityAvgPrice", communityAvgPrice);
            
            // 计算溢价率
            double cityPremiumRate = unitPrice > 0 && cityAvgPrice > 0 ? (unitPrice - cityAvgPrice) / cityAvgPrice * 100 : 0;
            double districtPremiumRate = unitPrice > 0 && districtAvgPrice > 0 ? (unitPrice - districtAvgPrice) / districtAvgPrice * 100 : 0;
            double communityPremiumRate = unitPrice > 0 && communityAvgPrice > 0 ? (unitPrice - communityAvgPrice) / communityAvgPrice * 100 : 0;
            
            result.put("cityPremiumRate", Math.round(cityPremiumRate * 100) / 100.0);
            result.put("districtPremiumRate", Math.round(districtPremiumRate * 100) / 100.0);
            result.put("communityPremiumRate", Math.round(communityPremiumRate * 100) / 100.0);
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/house-price-analysis/{}, 耗时: {}ms", id, (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取房源价格分析异常, id: {}", id, e);
            throw e;
        }
    }
    
    /**
     * 获取相似房源推荐
     */
    @GetMapping("/house/{id}/similar")
    @Operation(summary = "获取相似房源推荐", description = "根据ID获取与该房源相似的其他房源列表")
    public ResponseEntity<List<Map<String, Object>>> getSimilarHouses(
            @Parameter(description = "房源ID") @PathVariable String id) {
        logger.info("获取相似房源推荐，id={}", id);
        
        List<Map<String, Object>> similarHouses = new ArrayList<>();
        
        // 模拟相似房源数据
        for (int i = 1; i <= 5; i++) {
            Map<String, Object> house = new HashMap<>();
            house.put("id", "similar_" + i);
            house.put("title", "相似房源 " + i + " - 精装修三室两厅");
            house.put("totalPrice", 500.0 + i * 10);
            house.put("unitPrice", 5.0 + i * 0.1);
            house.put("area", 100.0 - i);
            house.put("layout", "3室2厅");
            house.put("decoration", "精装");
            similarHouses.add(house);
        }
        
        return ResponseEntity.ok(similarHouses);
    }
    
    /**
     * 获取所有城市列表
     */
    @GetMapping("/cities")
    @Operation(summary = "获取所有城市列表", description = "返回系统中所有可用的城市列表")
    public ResponseEntity<List<String>> getCities() {
        logger.info("获取所有城市列表");
        List<String> cities = housePriceAnalysisService.getAllCities();
        return ResponseEntity.ok(cities);
    }

    /**
     * 获取系统统计数据
     */
    @GetMapping("/system-statistics")
    @Operation(summary = "获取系统统计数据", description = "返回系统整体统计数据")
    public ResponseEntity<?> getSystemStatistics() {
        try {
            logger.info("API调用开始: /api/analysis/system-statistics");
            long startTime = System.currentTimeMillis();
            
            // 构建系统统计数据
            Map<String, Object> result = new HashMap<>();
            
            // 获取系统总房源数量
            Map<String, Integer> cityHouseCounts = housePriceAnalysisService.getCityHouseCount();
            int totalHouses = cityHouseCounts.values().stream().mapToInt(Integer::intValue).sum();
            result.put("totalHouses", totalHouses);
            
            // 获取城市数量
            int cityCount = housePriceAnalysisService.getAllCities().size();
            result.put("cityCount", cityCount);
            
            // 获取均价、最高价、最低价
            Map<String, Double> cityAvgPrice = housePriceAnalysisService.getCityAveragePrice();
            double avgPrice = 0.0;
            double maxPrice = 0.0;
            double minPrice = Double.MAX_VALUE;
            
            for (Double price : cityAvgPrice.values()) {
                avgPrice += price;
                maxPrice = Math.max(maxPrice, price);
                if (price > 0) {
                    minPrice = Math.min(minPrice, price);
                }
            }
            
            if (!cityAvgPrice.isEmpty()) {
                avgPrice /= cityAvgPrice.size();
            } else {
                minPrice = 0;
            }
            
            result.put("avgPrice", Math.round(avgPrice));
            result.put("maxPrice", Math.round(maxPrice));
            result.put("minPrice", Math.round(minPrice));
            
            // 系统最后更新时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            result.put("lastUpdateTime", dateFormat.format(new Date()));
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/system-statistics, 耗时: {}ms", (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取系统统计数据异常", e);
            throw e;
        }
    }

    /**
     * 获取热门城市数据
     */
    @GetMapping("/hot-cities")
    @Operation(summary = "获取热门城市数据", description = "返回房源数量排名前列的城市")
    public ResponseEntity<?> getHotCities() {
        try {
            logger.info("API调用开始: /api/analysis/hot-cities");
            long startTime = System.currentTimeMillis();
            
            // 获取城市房源数量统计
            Map<String, Integer> cityHouseCount = housePriceAnalysisService.getCityHouseCount();
            
            // 获取城市平均价格统计
            Map<String, Double> cityAvgPrice = housePriceAnalysisService.getCityAveragePrice();
            
            // 构建结果列表
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 对城市按房源数量降序排序
            List<Map.Entry<String, Integer>> sortedCities = new ArrayList<>(cityHouseCount.entrySet());
            sortedCities.sort((a, b) -> b.getValue().compareTo(a.getValue()));
            
            // 限制返回前5个城市
            int limit = Math.min(5, sortedCities.size());
            
            // 获取排名前列的城市
            for (int i = 0; i < limit; i++) {
                Map.Entry<String, Integer> entry = sortedCities.get(i);
                String cityName = entry.getKey();
                int houseCount = entry.getValue();
                double avgPrice = cityAvgPrice.getOrDefault(cityName, 0.0);
                
                // 计算该城市的单价（元/平方米）
                // 这里简化处理，假设每平方米单价是总价的1%
                double unitPrice = avgPrice / 100;
                
                // 构建城市数据
                Map<String, Object> cityData = new HashMap<>();
                cityData.put("city", cityName);
                cityData.put("houseCount", houseCount);
                cityData.put("avgPrice", avgPrice);
                cityData.put("avgUnitPrice", unitPrice);
                
                // 附加模拟的价格涨跌幅（-5%到+5%之间的随机值）
                double priceChange = -5.0 + Math.random() * 10.0;
                priceChange = Math.round(priceChange * 100) / 100.0;
                cityData.put("priceChange", priceChange);
                
                result.add(cityData);
            }
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/hot-cities, 返回城市数: {}, 耗时: {}ms", 
                      result.size(), (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取热门城市数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取指定城市的统计数据
     */
    @GetMapping("/city-statistics")
    @Operation(summary = "获取城市统计数据", description = "返回指定城市的统计数据")
    public ResponseEntity<?> getCityStatistics(
            @RequestParam @Parameter(description = "城市名称") String city) {
        try {
            logger.info("API调用开始: /api/analysis/city-statistics, 参数: city={}", city);
            long startTime = System.currentTimeMillis();
            
            // 构建城市统计结果
            Map<String, Object> result = new HashMap<>();
            result.put("city", city);
            
            // 获取城市房源总数
            Map<String, Integer> cityHouseCount = housePriceAnalysisService.getCityHouseCount();
            int totalHouses = cityHouseCount.getOrDefault(city, 0);
            result.put("totalHouses", totalHouses);
            result.put("houseCount", totalHouses); // 添加别名，与前端保持一致
            
            // 获取城市平均价格
            Map<String, Double> cityAvgPrice = housePriceAnalysisService.getCityAveragePrice();
            double avgPrice = cityAvgPrice.getOrDefault(city, 0.0);
            result.put("avgPrice", avgPrice);
            
            // 获取城市平均面积
            double avgArea = housePriceAnalysisService.getCityAverageArea(city);
            result.put("avgArea", avgArea);
            
            // 计算并添加平均单价（万元/平方米）
            double avgUnitPrice = 0.0;
            if (avgArea > 0) {
                // 计算平均单价: 总价(万元) / 面积(平方米)
                avgUnitPrice = avgPrice / avgArea;
            } else {
                // 从房源数据直接计算平均单价
                List<HouseInfo> houses = housePriceAnalysisService.searchHouses(city, null, null, null, null, null, null);
                double totalUnitPrice = 0.0;
                int count = 0;
                
                for (HouseInfo house : houses) {
                    if (house.getPrice() != null && house.getPrice().getUnitPrice() != null && house.getPrice().getUnitPrice() > 0) {
                        // 单价通常以元/平方米存储，转换为万元/平方米
                        totalUnitPrice += house.getPrice().getUnitPrice() / 10000.0;
                        count++;
                    }
                }
                
                if (count > 0) {
                    avgUnitPrice = totalUnitPrice / count;
                }
            }
            
            // 确保单价不为零
            if (avgUnitPrice < 0.01 && totalHouses > 0) {
                // 如果计算结果接近零但有房源，设置一个估计值
                avgUnitPrice = avgPrice > 0 ? avgPrice / 100 : 0.5; // 假设100平米作为默认面积
            }
            
            result.put("avgUnitPrice", avgUnitPrice);
            
            // 获取城市价格统计数据
            Map<String, Double> cityMedianPrice = housePriceAnalysisService.getCityMedianPrice();
            double medianPrice = cityMedianPrice.getOrDefault(city, 0.0);
            
            // 从数据库获取最高价和最低价
            List<HouseInfo> houses = housePriceAnalysisService.searchHouses(city, null, null, null, null, null, null);
            double maxPrice = 0.0;
            double minPrice = Double.MAX_VALUE;
            
            for (HouseInfo house : houses) {
                if (house.getPrice() != null && house.getPrice().getTotalPrice() != null) {
                    maxPrice = Math.max(maxPrice, house.getPrice().getTotalPrice());
                    if (house.getPrice().getTotalPrice() > 0) {
                        minPrice = Math.min(minPrice, house.getPrice().getTotalPrice());
                    }
                }
            }
            
            if (houses.isEmpty() || minPrice == Double.MAX_VALUE) {
                minPrice = 0.0;
            }
            
            result.put("maxPrice", Math.round(maxPrice));
            result.put("minPrice", Math.round(minPrice));
            result.put("medianPrice", Math.round(medianPrice));
            
            // 从数据库获取最大、最小面积
            double maxArea = 0.0;
            double minArea = Double.MAX_VALUE;
            
            for (HouseInfo house : houses) {
                Double area = house.getAreaValue();
                if (area != null) {
                    maxArea = Math.max(maxArea, area);
                    if (area > 0) {
                        minArea = Math.min(minArea, area);
                    }
                }
            }
            
            if (houses.isEmpty() || minArea == Double.MAX_VALUE) {
                minArea = 0.0;
            }
            
            result.put("maxArea", maxArea);
            result.put("minArea", minArea);
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/city-statistics, 城市: {}, 耗时: {}ms", city, (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取城市统计数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取价格分布数据
     */
    @GetMapping("/price-distribution")
    @Operation(summary = "获取价格分布数据", description = "返回指定城市的房价分布数据")
    public ResponseEntity<?> getPriceDistribution(
            @RequestParam @Parameter(description = "城市名称") String city) {
        try {
            logger.info("API调用开始: /api/analysis/price-distribution, 参数: city={}", city);
            long startTime = System.currentTimeMillis();

            // 获取价格分布数据
            Map<String, Map<String, Integer>> priceDistribution = housePriceAnalysisService.getCityPriceDistribution();
            Map<String, Integer> cityPriceDistribution = priceDistribution.getOrDefault(city, new HashMap<>());

            // 构建结果
            Map<String, Object> result = new HashMap<>();
            result.put("city", city);

            // 获取所有价格区间
            List<String> ranges = new ArrayList<>(cityPriceDistribution.keySet());
            
            // 按照价格区间排序
            ranges.sort((a, b) -> {
                double aValue = extractLowerBound(a);
                double bValue = extractLowerBound(b);
                return Double.compare(aValue, bValue);
            });
            
            // 提取价格区间和对应的数量
            List<Integer> counts = new ArrayList<>();
            List<Map<String, Object>> chartData = new ArrayList<>();
            
            // 直接将价格区间和数量存储为对象，用于CityComparison页面
            Map<String, Integer> priceDistributionMap = new HashMap<>();
            
            for (String range : ranges) {
                int count = cityPriceDistribution.getOrDefault(range, 0);
                counts.add(count);
                
                // 将价格区间和数量添加到Map
                priceDistributionMap.put(range, count);
                
                Map<String, Object> item = new HashMap<>();
                item.put("name", range);
                item.put("value", count);
                chartData.add(item);
            }

            // 添加两种数据格式以兼容不同前端图表组件
            result.put("ranges", ranges);
            result.put("counts", counts);
            result.put("data", chartData); // 饼图格式
            result.put("priceDistribution", priceDistributionMap); // 为CityComparison页面提供的key-value格式

            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/price-distribution, 城市: {}, 价格区间数: {}, 耗时: {}ms", 
                      city, ranges.size(), (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取价格分布数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }
    
    /**
     * 提取价格区间的下限
     */
    private double extractLowerBound(String range) {
        try {
            if (range.endsWith("以下")) {
                return 0;
            } else if (range.endsWith("以上")) {
                String numStr = range.substring(0, range.indexOf("以上")).trim();
                if (numStr.endsWith("万") || numStr.endsWith("元/㎡")) {
                    numStr = numStr.substring(0, numStr.length() - 1);
                }
                return Double.parseDouble(numStr);
            } else if (range.contains("-")) {
                String[] parts = range.split("-");
                String minStr = parts[0].trim();
                if (minStr.endsWith("万") || minStr.endsWith("元/㎡")) {
                    minStr = minStr.substring(0, minStr.length() - 1);
                }
                return Double.parseDouble(minStr);
            }
        } catch (Exception e) {
            // 解析失败，返回0
        }
        return 0;
    }

    /**
     * 获取面积分布数据
     */
    @GetMapping("/area-distribution")
    @Operation(summary = "获取面积分布数据", description = "返回指定城市的面积分布数据")
    public ResponseEntity<Map<String, Object>> getAreaDistribution(
            @RequestParam @Parameter(description = "城市名称") String city) {
        try {
            logger.info("API调用开始: /api/analysis/area-distribution, 参数: city={}", city);
            long startTime = System.currentTimeMillis();
            
            // 获取城市面积分布
            Map<String, Map<String, Integer>> areaDistribution = housePriceAnalysisService.getCityAreaDistribution();
            Map<String, Integer> cityAreaDistribution = areaDistribution.getOrDefault(city, new HashMap<>());
            
            // 构建结果
            Map<String, Object> result = new HashMap<>();
            result.put("city", city);
            
            // 提取标签和数量
            List<String> labels = new ArrayList<>(cityAreaDistribution.keySet());
            List<Integer> counts = new ArrayList<>();
            List<Map<String, Object>> chartData = new ArrayList<>();
            
            // 直接将面积区间和数量存储为对象，用于CityComparison页面
            Map<String, Integer> areaDistributionMap = new HashMap<>();
            
            // 按照面积区间排序
            labels.sort((a, b) -> {
                // 提取面积区间的下限进行比较
                double aValue = extractLowerBound(a);
                double bValue = extractLowerBound(b);
                return Double.compare(aValue, bValue);
            });
            
            // 获取排序后的数量
            for (String label : labels) {
                int count = cityAreaDistribution.get(label);
                counts.add(count);
                
                // 将面积区间和数量添加到Map
                areaDistributionMap.put(label, count);
                
                Map<String, Object> item = new HashMap<>();
                item.put("name", label);
                item.put("value", count);
                chartData.add(item);
            }
            
            // 添加两种数据格式以兼容不同前端图表组件
            result.put("labels", labels);
            result.put("ranges", labels); // 添加别名，与前端保持一致
            result.put("counts", counts);
            result.put("data", chartData); // 饼图格式
            result.put("areaDistribution", areaDistributionMap); // 为CityComparison页面提供的key-value格式
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/area-distribution, 城市: {}, 面积区间数: {}, 耗时: {}ms", 
                    city, labels.size(), (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取面积分布数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取户型分布数据
     */
    @GetMapping("/layout-distribution")
    @Operation(summary = "获取户型分布数据", description = "返回指定城市的户型分布数据")
    public ResponseEntity<Map<String, Object>> getLayoutDistribution(
            @RequestParam @Parameter(description = "城市名称") String city) {
        try {
            logger.info("API调用开始: /api/analysis/layout-distribution, 参数: city={}", city);
            long startTime = System.currentTimeMillis();
            
            // 获取城市户型分布
            Map<String, Map<String, Integer>> layoutDistribution = housePriceAnalysisService.getCityLayoutDistribution();
            Map<String, Integer> cityLayoutDistribution = layoutDistribution.getOrDefault(city, new HashMap<>());
            
            // 构建结果
            Map<String, Object> result = new HashMap<>();
            result.put("city", city);
            
            // 提取户型和数量
            List<Map.Entry<String, Integer>> entries = new ArrayList<>(cityLayoutDistribution.entrySet());
            
            // 按照数量降序排序
            entries.sort((a, b) -> b.getValue().compareTo(a.getValue()));
            
            // 取前10个户型
            List<String> layouts = new ArrayList<>();
            List<Integer> counts = new ArrayList<>();
            List<Map<String, Object>> detailData = new ArrayList<>();
            
            int count = 0;
            for (Map.Entry<String, Integer> entry : entries) {
                if (count >= 10) break;
                String layout = entry.getKey();
                int layoutCount = entry.getValue();
                
                layouts.add(layout);
                counts.add(layoutCount);
                
                Map<String, Object> detailItem = new HashMap<>();
                detailItem.put("name", layout);
                detailItem.put("value", layoutCount);
                detailData.add(detailItem);
                
                count++;
            }
            
            // 添加两种格式数据，兼容不同的前端图表组件
            result.put("layouts", layouts);
            result.put("counts", counts);
            result.put("data", detailData);  // 饼图可能使用这种格式 [{name,value}]
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/layout-distribution, 城市: {}, 耗时: {}ms", city, (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取户型分布数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取装修分布数据
     */
    @GetMapping("/decoration-distribution")
    @Operation(summary = "获取装修分布数据", description = "返回指定城市的装修分布数据")
    public ResponseEntity<Map<String, Object>> getDecorationDistribution(
            @RequestParam @Parameter(description = "城市名称") String city) {
        try {
            logger.info("API调用开始: /api/analysis/decoration-distribution, 参数: city={}", city);
            long startTime = System.currentTimeMillis();
            
            // 获取城市装修分布
            Map<String, Map<String, Integer>> decorationDistribution = housePriceAnalysisService.getCityDecorationDistribution();
            Map<String, Integer> cityDecorationDistribution = decorationDistribution.getOrDefault(city, new HashMap<>());
            
            // 构建结果
            Map<String, Object> result = new HashMap<>();
            result.put("city", city);
            
            // 提取装修类型和数量
            List<Map.Entry<String, Integer>> entries = new ArrayList<>(cityDecorationDistribution.entrySet());
            
            // 按照数量降序排序
            entries.sort((a, b) -> b.getValue().compareTo(a.getValue()));
            
            // 提取排序后的数据
            List<String> decorations = new ArrayList<>();
            List<Integer> counts = new ArrayList<>();
            List<Map<String, Object>> chartData = new ArrayList<>();
            
            for (Map.Entry<String, Integer> entry : entries) {
                String deco = entry.getKey();
                int count = entry.getValue();
                
                decorations.add(deco);
                counts.add(count);
                
                Map<String, Object> item = new HashMap<>();
                item.put("name", deco);
                item.put("value", count);
                chartData.add(item);
            }
            
            // 添加两种数据格式以兼容不同前端图表组件
            result.put("decorations", decorations);
            result.put("counts", counts);
            result.put("data", chartData);  // 饼图格式
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/decoration-distribution, 城市: {}, 装修类型数: {}, 耗时: {}ms", 
                    city, decorations.size(), (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取装修分布数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取价格-面积散点图数据
     */
    @GetMapping("/price-area-scatter")
    @Operation(summary = "获取价格-面积散点图数据", description = "返回指定城市的价格与面积关系散点图数据")
    public ResponseEntity<Map<String, Object>> getPriceAreaScatter(
            @RequestParam @Parameter(description = "城市名称") String city) {
        try {
            logger.info("API调用开始: /api/analysis/price-area-scatter, 参数: city={}", city);
            long startTime = System.currentTimeMillis();
            
            // 获取城市房源数据
            Option scatterOption = housePriceAnalysisService.getPriceAreaScatterData(city);
            
            // 提取面积和价格数据
            List<Double> areas = new ArrayList<>();
            List<Double> prices = new ArrayList<>();
            List<Map<String, Object>> points = new ArrayList<>();
            
            // 处理图表数据
            if (scatterOption != null && scatterOption.series() != null && !scatterOption.series().isEmpty()) {
                for (Series series : scatterOption.series()) {
                    if (series instanceof Scatter) {
                        Scatter scatter = (Scatter) series;
                        List<Object> dataPoints = scatter.data();
                        
                        if (dataPoints != null) {
                            for (Object dataPoint : dataPoints) {
                                if (dataPoint instanceof Object[]) {
                                    Object[] point = (Object[]) dataPoint;
                                    if (point.length >= 2) {
                                        if (point[0] instanceof Number && point[1] instanceof Number) {
                                            double area = ((Number) point[0]).doubleValue();
                                            double price = ((Number) point[1]).doubleValue();
                                            areas.add(area);
                                            prices.add(price);
                                            
                                            // 创建点对象
                                            Map<String, Object> pointMap = new HashMap<>();
                                            pointMap.put("area", area);
                                            pointMap.put("price", price);
                                            points.add(pointMap);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            // 计算相关系数
            double correlation = 0.0;
            if (!areas.isEmpty() && !prices.isEmpty()) {
                // 简单计算相关系数
                int n = areas.size();
                double sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0, sumY2 = 0;
                
                for (int i = 0; i < n; i++) {
                    double x = areas.get(i);
                    double y = prices.get(i);
                    
                    sumX += x;
                    sumY += y;
                    sumXY += x * y;
                    sumX2 += x * x;
                    sumY2 += y * y;
                }
                
                double numerator = n * sumXY - sumX * sumY;
                double denominator = Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY));
                
                if (denominator != 0) {
                    correlation = numerator / denominator;
                }
            }
            
            // 构建结果
            Map<String, Object> result = new HashMap<>();
            result.put("city", city);
            result.put("areas", areas);
            result.put("prices", prices);
            result.put("points", points); // 添加points属性，兼容前端可能需要的数据格式
            result.put("correlation", correlation);
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/price-area-scatter, 耗时: {}ms, 数据点数量: {}", 
                    (endTime - startTime), areas.size());
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取价格-面积散点图数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body(error);
        }
    }

    /**
     * 获取区域分析数据
     */
    @GetMapping("/district-analysis")
    @Operation(summary = "获取区域分析数据", description = "返回指定城市的各区域统计分析数据")
    public ResponseEntity<List<Map<String, Object>>> getDistrictAnalysis(
            @RequestParam @Parameter(description = "城市名称") String city) {
        try {
            logger.info("API调用开始: /api/analysis/district-analysis, 参数: city={}", city);
            long startTime = System.currentTimeMillis();
            
            // 获取城市的区域列表
            List<String> districts = housePriceAnalysisService.getDistrictsByCity(city);
            
            // 获取区域房源数量
            Map<String, Integer> districtCounts = housePriceAnalysisService.getDistrictHouseCounts(city);
            
            // 构建结果
            List<Map<String, Object>> result = new ArrayList<>();
            
            // 获取城市平均价格
            Map<String, Double> cityAvgPrice = housePriceAnalysisService.getCityAveragePrice();
            double avgCityPrice = cityAvgPrice.getOrDefault(city, 0.0);
            
            for (String district : districts) {
                Map<String, Object> districtData = new HashMap<>();
                districtData.put("district", district);
                
                // 房源数量
                int houseCount = districtCounts.getOrDefault(district, 0);
                districtData.put("houseCount", houseCount);
                districtData.put("totalHouses", houseCount);  // 添加totalHouses字段以匹配前端期望
                
                // 区域平均价格 (模拟数据，根据城市平均价格随机波动)
                double multiplier = 0.8 + Math.random() * 0.4;  // 生成0.8到1.2之间的随机系数
                double avgPrice = avgCityPrice * multiplier;
                districtData.put("avgPrice", Math.round(avgPrice * 100) / 100.0);
                
                // 区域最大和最小价格
                double maxPrice = avgPrice * (1.1 + Math.random() * 0.3); // 平均价格的1.1-1.4倍
                double minPrice = avgPrice * (0.6 + Math.random() * 0.2); // 平均价格的0.6-0.8倍
                districtData.put("maxPrice", Math.round(maxPrice * 100) / 100.0);
                districtData.put("minPrice", Math.round(minPrice * 100) / 100.0);
                
                // 区域平均面积 (模拟数据，80-120平方米之间随机)
                double avgArea = 80 + Math.random() * 40;
                districtData.put("avgArea", Math.round(avgArea * 100) / 100.0);
                
                result.add(districtData);
            }
            
            long endTime = System.currentTimeMillis();
            logger.info("API调用结束: /api/analysis/district-analysis, 城市: {}, 区域数: {}, 耗时: {}ms", 
                    city, districts.size(), (endTime - startTime));
            
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("获取区域分析数据异常: ", e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("message", "系统内部错误");
            error.put("error", e.getMessage());
            return ResponseEntity.status(500).body((List)Collections.singletonList(error));
        }
    }

    /**
     * 获取区域详情数据
     */
    @GetMapping("/district-detail")
    @Operation(summary = "获取区域详情数据", description = "返回指定城市区域的详细分析数据")
    public ResponseEntity<Map<String, Object>> getDistrictDetail(
            @RequestParam @Parameter(description = "城市名称") String city,
            @RequestParam @Parameter(description = "区域名称") String district) {
        logger.info("获取区域详情数据，城市={}，区域={}", city, district);
        
        Map<String, Object> result = new HashMap<>();
        result.put("city", city);
        result.put("district", district);
        
        // 获取区域房源数量
        Map<String, Integer> districtCounts = housePriceAnalysisService.getDistrictHouseCounts(city);
        int houseCount = districtCounts.getOrDefault(district, 0);
        result.put("houseCount", houseCount);
        
        // 获取指定城市和区域的房源
        List<HouseInfo> houses = housePriceAnalysisService.searchHouses(city, null, null, null, null, null, district);
        
        // 计算区域价格统计
        double totalUnitPrice = 0;
        double totalPrice = 0;
        double maxPrice = 0;
        double minPrice = Double.MAX_VALUE;
        int priceCount = 0;
        
        for (HouseInfo house : houses) {
            if (house.getPrice() != null) {
                if (house.getPrice().getUnitPrice() != null) {
                    totalUnitPrice += house.getPrice().getUnitPrice();
                    priceCount++;
                }
                
                if (house.getPrice().getTotalPrice() != null) {
                    double price = house.getPrice().getTotalPrice();
                    totalPrice += price;
                    maxPrice = Math.max(maxPrice, price);
                    if (price > 0) {
                        minPrice = Math.min(minPrice, price);
                    }
                }
            }
        }
        
        double avgPrice = priceCount > 0 ? totalUnitPrice / priceCount : 0;
        if (houses.isEmpty() || minPrice == Double.MAX_VALUE) {
            minPrice = 0;
        }
        
        result.put("avgPrice", avgPrice);
        result.put("maxPrice", maxPrice);
        result.put("minPrice", minPrice);
        
        // 计算区域面积统计
        double totalArea = 0;
        double maxArea = 0;
        double minArea = Double.MAX_VALUE;
        int areaCount = 0;
        
        for (HouseInfo house : houses) {
            Double area = house.getAreaValue();
            if (area != null && area > 0) {
                totalArea += area;
                areaCount++;
                maxArea = Math.max(maxArea, area);
                minArea = Math.min(minArea, area);
            }
        }
        
        double avgArea = areaCount > 0 ? totalArea / areaCount : 0;
        if (houses.isEmpty() || minArea == Double.MAX_VALUE) {
            minArea = 0;
        }
        
        result.put("avgArea", avgArea);
        result.put("maxArea", maxArea);
        result.put("minArea", minArea);
        
        // 获取区域内的社区列表及其统计信息
        Map<String, List<HouseInfo>> communitiesMap = houses.stream()
                .filter(h -> h.getCommunity() != null && !h.getCommunity().isEmpty())
                .collect(Collectors.groupingBy(HouseInfo::getCommunity));
        
        List<Map<String, Object>> communities = new ArrayList<>();
        for (Map.Entry<String, List<HouseInfo>> entry : communitiesMap.entrySet()) {
            String communityName = entry.getKey();
            List<HouseInfo> communityHouses = entry.getValue();
            
            // 计算社区均价
            double communityTotalPrice = 0;
            int communityPriceCount = 0;
            
            for (HouseInfo house : communityHouses) {
                if (house.getPrice() != null && house.getPrice().getUnitPrice() != null) {
                    communityTotalPrice += house.getPrice().getUnitPrice();
                    communityPriceCount++;
                }
            }
            
            double communityAvgPrice = communityPriceCount > 0 ? communityTotalPrice / communityPriceCount : 0;
            
            Map<String, Object> communityData = new HashMap<>();
            communityData.put("community", communityName);
            communityData.put("houseCount", communityHouses.size());
            communityData.put("avgPrice", communityAvgPrice);
            
            communities.add(communityData);
        }
        
        result.put("communities", communities);
        
        // 获取区域内的户型分布统计
        Map<String, List<HouseInfo>> layoutsMap = houses.stream()
                .filter(h -> h.getLayout() != null && !h.getLayout().isEmpty())
                .collect(Collectors.groupingBy(HouseInfo::getLayout));
        
        List<Map<String, Object>> layouts = new ArrayList<>();
        for (Map.Entry<String, List<HouseInfo>> entry : layoutsMap.entrySet()) {
            String layoutName = entry.getKey();
            List<HouseInfo> layoutHouses = entry.getValue();
            
            // 计算户型均价
            double layoutTotalPrice = 0;
            int layoutPriceCount = 0;
            
            for (HouseInfo house : layoutHouses) {
                if (house.getPrice() != null && house.getPrice().getUnitPrice() != null) {
                    layoutTotalPrice += house.getPrice().getUnitPrice();
                    layoutPriceCount++;
                }
            }
            
            double layoutAvgPrice = layoutPriceCount > 0 ? layoutTotalPrice / layoutPriceCount : 0;
            
            Map<String, Object> layoutData = new HashMap<>();
            layoutData.put("layout", layoutName);
            layoutData.put("houseCount", layoutHouses.size());
            layoutData.put("avgPrice", layoutAvgPrice);
            
            layouts.add(layoutData);
        }
        
        result.put("layouts", layouts);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 城市对比分析
     */
    @PostMapping("/city-comparison")
    @Operation(summary = "城市对比分析", description = "对比多个城市的房价数据")
    public ResponseEntity<Map<String, Object>> compareCities(@RequestBody Map<String, List<String>> request) {
        List<String> cities = request.get("cities");
        logger.info("城市对比分析，城市列表={}", cities);
        
        if (cities == null || cities.isEmpty()) {
            return ResponseEntity.badRequest().body(Collections.singletonMap("error", "城市列表不能为空"));
        }
        
        Map<String, Object> result = new HashMap<>();
        result.put("cities", cities);
        
        // 获取城市平均价格
        Map<String, Double> cityAvgPrice = housePriceAnalysisService.getCityAveragePrice();
        List<Double> avgPrices = new ArrayList<>();
        
        for (String city : cities) {
            avgPrices.add(cityAvgPrice.getOrDefault(city, 0.0));
        }
        result.put("avgPrices", avgPrices);
        
        // 获取城市平均面积
        List<Double> avgAreas = new ArrayList<>();
        for (String city : cities) {
            double avgArea = housePriceAnalysisService.getCityAverageArea(city);
            avgAreas.add(avgArea);
        }
        result.put("avgAreas", avgAreas);
        
        return ResponseEntity.ok(result);
    }

    /**
     * 获取指定城市的区域列表
     */
    @GetMapping("/districts")
    @Operation(summary = "获取指定城市的区域列表", description = "返回指定城市的所有区域列表")
    public ResponseEntity<List<String>> getDistricts(
            @Parameter(description = "城市名称") @RequestParam String city) {
        logger.info("获取城市[{}]的区域列表", city);
        List<String> districts = housePriceAnalysisService.getDistrictsByCity(city);
        return ResponseEntity.ok(districts);
    }
}